package com.jackrain.nea.wms.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.util.TypeUtils;
import com.aliyun.openservices.ons.api.Message;
import com.jackrain.nea.config.PropertiesConf;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.fc.dl.api.WmsTranOutBoxSaveCmd;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.ReferenceUtil;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.utils.ObjectToUtil;
import com.jackrain.nea.wms.mapper.WmsSqlMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 拣货装箱单回传->FC
 *
 * @author zhang.zz
 * @create 2018/10/19
 */
@Service("com.jackrain.fc.service.WmsTranOutBoxService")
@Slf4j
public class WmsTranOutBoxService implements BaseProcess {

    @Reference(version = "1.0", group = "dl")
    private WmsTranOutBoxSaveCmd wmsTranOutBoxSaveCmd;
    @Autowired
    private WmsSqlMapper wmsSqlMapper;
    @Autowired
    private PropertiesConf pconf;

    private final String TABLE_NAME = "WMS_T_RESULT_OUT";
    private static final int STATUS_ING = 00;
    private static final int STATUS_SUCCESS = 99;
    private static final int STATUS_FAILED = 90;

    @Override
    public ValueHolder process(JSONObject paramObject, Message message) throws Exception {

        ValueHolder valueHolder = new ValueHolder();
        if (null == paramObject || paramObject.size() <= 0) {
            return valueHolder;
        }
        List<HashMap> list = (List<HashMap>) paramObject.get("list");
        JSONObject retStr = requestData(list);
        valueHolder.put("retStr", retStr);
        return valueHolder;
    }
    @Override
    public List<HashMap> queryData(int pageSize) {

        WmsTranOutBoxService wmsTranOutBoxService = ApplicationContextHandle.getBean("com.jackrain.fc.service.WmsTranOutBoxService");
        List<HashMap> listArr = new ArrayList();
        //查询wms_bill_no
        String whereStr = " RETRY_COUNT < 5 AND BOX_STATUS = '80' AND BILL_TYPE = 'TO' AND RECIVE_STATUS = '99' ";//80未处理
        String[] field = new String[]{"WMS_BILL_NO"};
        String order = " WHERE " + whereStr;
        String limit = String.valueOf(pageSize);
        List<HashMap> wms_bill_no_list = wmsSqlMapper.select4(TABLE_NAME, field, order, limit);
        //未处理的没有再查询失败的
        if (wms_bill_no_list == null || wms_bill_no_list.size() <= 0) {
            whereStr = " RETRY_COUNT < 5 AND BOX_STATUS = '90' AND BILL_TYPE = 'TO'  AND RECIVE_STATUS = '99' ";//90失败
            order = " WHERE " + whereStr;
            wms_bill_no_list = wmsSqlMapper.select4(TABLE_NAME, field, order, limit);
        }
        //去除重复
        JSONArray wms_bill_no_jsonarray = new JSONArray();
        for (HashMap hashMap :wms_bill_no_list){
            int countArr = 0;
            String wms_bill_no =(String) hashMap.get("WMS_BILL_NO");
            for(int n=0;n<wms_bill_no_jsonarray.size();n++){
                if(!(wms_bill_no.equals(wms_bill_no_jsonarray.getString(n)))){
                    countArr++;
                }
            }
            if (countArr==wms_bill_no_jsonarray.size()) {
                wms_bill_no_jsonarray.add(wms_bill_no);
            }
        }
        for(int i=0;i<wms_bill_no_jsonarray.size();i++){
            String wms_bill_no =(String) wms_bill_no_jsonarray.get(i);
            String whereStrs = " BILL_TYPE = 'TO' AND BOX_STATUS = '80' AND WMS_BILL_NO = '"+ wms_bill_no + "'";//00未处理
            String[] fields = new String[]{" OBJID, WMS_BILL_NO, BILL_NO ,RECIVE_STATUS ,RETRY_COUNT "};
            String orders = " WHERE " + whereStrs;
            String limits = String.valueOf(pageSize);
            List<HashMap> list = wmsSqlMapper.select4(TABLE_NAME, fields, orders, limits);
            //未处理的没有再查询失败的
            if (list == null || list.size() <= 0) {
                whereStrs = " BILL_TYPE = 'TO' AND BOX_STATUS = '90' AND WMS_BILL_NO = '"+ wms_bill_no + "'";//90失败
                orders = " WHERE " + whereStrs;
                list = wmsSqlMapper.select4(TABLE_NAME, fields, orders, limits);
            }
            if (!(list == null || list.size() <= 0)) {
                int count = 0;
                for(int j=0;j<list.size();j++){
                    JSONObject jsonObject = new JSONObject(list.get(j));
                    if((jsonObject.getLong("RECIVE_STATUS")==99)&&(jsonObject.getLong("RETRY_COUNT")<5)){
                        count++;
                    }
                }
                if(count==list.size()){
                    //修改为处理中
                    wmsTranOutBoxService.batchSave(list, STATUS_ING);
                    HashMap map = new HashMap();
                    map.put("list",list);
                    listArr.add(map);
                }
            }
        }
        log.info("WmsTranOutBoxService--listArr-->{}",listArr);

        return listArr;
    }
    private JSONObject requestData(List<HashMap> list) {

        JSONObject retObject = new JSONObject();
        WmsTranOutBoxService wmsTranOutBoxService = ApplicationContextHandle.getBean("com.jackrain.fc.service.WmsTranOutBoxService");
        if (list == null) {
            return retObject;
        }
        retObject.put("dataCount", list.size());
        //处理数据
        JSONArray postArray = new JSONArray();
        for (int i = 0; i < list.size(); i++) {
            JSONArray jsonArray = new JSONArray();
            //bill_no
            JSONArray bill_no_jsonArray = new JSONArray();
            //wms_bill_no
            String wms_bill_no = "";
            //objid
            Long objid = null;

            JSONObject jsonObject = new JSONObject(list.get(i));
            List<HashMap> list1 =(List) jsonObject.get("list");
            for(int j=0;j<list1.size();j++){
                JSONObject Object = new JSONObject(list1.get(j));
                bill_no_jsonArray.add(Object.get("BILL_NO"));
                if(j==0){
                    wms_bill_no =(String) Object.get("WMS_BILL_NO");
                    objid = Object.getLong("OBJID");
                }
            }
            jsonArray.add(bill_no_jsonArray);
            jsonArray.add(wms_bill_no);
            jsonArray.add(objid);
            //总数据
            postArray.add(jsonArray);
        }
        //同步post
        try {
            JSONObject returnJson = doPost(postArray);
            log.info("WmsTranOutBoxService--returnJson-->{}",returnJson);

            retObject.put("ret", returnJson);
            if (returnJson == null || returnJson.size() <= 0) {
                //修改为失败
                wmsTranOutBoxService.batchSave(list, STATUS_FAILED);
                throw new NDSException("服务端没有数据，请求参数" + postArray.toJSONString());
            } else {
                Long code = returnJson.getLong("code");
                if (code == null || code != 0) {
                    //再修改为成功
                    JSONArray successIds = returnJson.getJSONArray("successIds");
                    if (successIds != null && successIds.size() > 0) {
                        wmsTranOutBoxService.batchSave(successIds, STATUS_SUCCESS);
                    }
                    //更新中间表数据
                    JSONArray errorArray = returnJson.getJSONArray("error");
                    wmsTranOutBoxService.saveWmsError(errorArray);
                    throw new NDSException("服务端保存出错，" + returnJson);
                }

                if (0 == code) {
                    JSONArray successIds = returnJson.getJSONArray("successIds");
                    wmsTranOutBoxService.batchSave(successIds, STATUS_SUCCESS);
                }
            }
        } catch (Exception e) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            if ((e instanceof NDSException)) {
                throw e;
            } else {
                //修改为失败
                wmsTranOutBoxService.batchSave(list, STATUS_FAILED);
                throw new NDSException(sw.toString());
            }
        }
        return retObject;
    }

    private JSONObject doPost(JSONArray postArrayRow) {

        long startTime = System.currentTimeMillis();
        JSONObject data = new JSONObject();
        data.put("data", postArrayRow);

        ValueHolder result = new ValueHolder();
        try {
            HashMap map = new HashMap(1);
            map.put("param", data);
            Object o = ReferenceUtil.refer(ApplicationContextHandle.getApplicationContext(), "com.jackrain.nea.fc.dl.api.WmsTranOutBoxSaveCmd", "dl", "1.0");
            result = ((WmsTranOutBoxSaveCmd) o).execute(map);
            if (result == null) {
                result = new ValueHolder();
                result.put("code", -1);
                result.put("error", "服务错误：返回为空");
            }
            if (result.get("code") == null) {
                result.put("code", 0);
            }
        } catch (Exception e) {
            result.put("code", -1);
            if (e instanceof NDSException) {
                result.put("error", "服务错误：" + e.getMessage());
            } else {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                e.printStackTrace(pw);
                result.put("error", "服务错误：" + sw.toString());
            }
        }
        double spendTime = (double) (System.currentTimeMillis() - startTime) / 1000.0D;
        result.put("doPostSpendTime", spendTime);
        return result.toJSONObject();
    }
    public void batchSave(JSONArray dataArray, int status) {
        log.debug("dataArray--------->"+dataArray);
        if (dataArray == null) {
            return;
        }
        for (int a = 0; a < dataArray.size(); a++) {
            JSONObject jsonObject = dataArray.getJSONObject(a);
            String wms_bill_no = jsonObject.getString("wms_bill_no");
            Long objid = jsonObject.getLong("objid");
            if (ObjectToUtil.isNullOREmpty(String.valueOf(wms_bill_no))) {
                continue;
            }
            JSONObject setKeys = new JSONObject();
            setKeys.put("BOX_STATUS", status);//
            setKeys.put("OBJID", objid);//
            setKeys.put("FC_HANDLETIME", new Timestamp(System.currentTimeMillis()));//处理时间
            if (STATUS_SUCCESS == status) {
                setKeys.put("ERROR_LOG", "");//
            }
            JSONObject whereKeys = new JSONObject();
            whereKeys.put("WMS_BILL_NO",wms_bill_no);
            wmsSqlMapper.update(TABLE_NAME, setKeys, whereKeys);
        }
    }
    //修改状态
    public void batchSave(List<HashMap> list, int status) {
        if (list == null) {
            return;
        }
        //修改状态
        for (int i = 0; i < list.size(); i++) {
            JSONObject jsonObject = new JSONObject(list.get(i));
            if (jsonObject == null) {
                continue;
            }
            String wms_bill_no = jsonObject.getString("WMS_BILL_NO");
            if (ObjectToUtil.isNullOREmpty(String.valueOf(wms_bill_no))) {
                continue;
            }
            JSONObject setKeys = new JSONObject();
            setKeys.put("BOX_STATUS", status);//
            setKeys.put("FC_HANDLETIME", new Timestamp(System.currentTimeMillis()));//处理时间
            if (STATUS_SUCCESS == status) {
                setKeys.put("ERROR_LOG", "");//
            }
            if (STATUS_FAILED == status) {
                int retrycount = retryCount(wms_bill_no);
                setKeys.put("RETRY_COUNT", retrycount + 1);
            }
            JSONObject whereKeys = new JSONObject();
            whereKeys.put("WMS_BILL_NO",wms_bill_no);
            wmsSqlMapper.update(TABLE_NAME, setKeys, whereKeys);
        }
    }
    /**
     * 状态为失败时调用累计重试次数
     */
    private int retryCount(String wms_bill_no) {
        JSONObject whereKeys = new JSONObject();
        whereKeys.put("WMS_BILL_NO",wms_bill_no);
        List<HashMap> retryList = wmsSqlMapper.select(TABLE_NAME, new String[]{"RETRY_COUNT"}, whereKeys);
        log.debug("restryList--------->"+retryList);
        Integer retrycount = 0;
        if(retryList.size()==0){
            return retrycount;
        }
        HashMap hashMap = retryList.get(0);
        retrycount = TypeUtils.castToInt(hashMap.get("RETRY_COUNT"));
        if(retrycount==null){
            return 0;
        }
        return retrycount;
    }
    public void saveWmsError(JSONArray errorArray) {

        if (errorArray == null) {
            return;
        }
        //修改状态
        for (int i = 0; i < errorArray.size(); i++) {
            JSONObject errorObject = errorArray.getJSONObject(i);
            if (errorObject == null) {
                continue;
            }
            String wms_bill_no = errorObject.getString("key");
            Long objid = errorObject.getLong("objid");
            if (ObjectToUtil.isNullOREmpty(String.valueOf(wms_bill_no))) {
                continue;
            }
            JSONObject whereKeys = new JSONObject();
            whereKeys.put("WMS_BILL_NO",wms_bill_no);
            int retryCount = retryCount(wms_bill_no);
            String msg = errorObject.getString("message");
            JSONObject setKeys = new JSONObject();
            if (!ObjectToUtil.isNullOREmpty(msg)) {
                setKeys.put("ERROR_LOG", msg);//
            }
            setKeys.put("BOX_STATUS", STATUS_FAILED);//失败
            setKeys.put("FC_HANDLETIME", new Timestamp(System.currentTimeMillis()));//处理时间
            setKeys.put("RETRY_COUNT", retryCount + 1);
            wmsSqlMapper.update(TABLE_NAME, setKeys, whereKeys);
        }
    }

}
